<?php

/**
 * Files model
 *
 */
class Application_Model_File
{
    const UPLOAD_DIR='data/uploads';
    const RESOURCE_NAME='file';
    
    /**
     * Deletes file
     *
     * @param string $filename
     * @return bool
     */
    static function delete($filename)
    {
        if (!self::isValidFile($filename)) return false;
        
        if (file_exists(ROOT_DIR.'/'.self::UPLOAD_DIR.'/'.$filename))
        {
            return @unlink(ROOT_DIR.'/'.self::UPLOAD_DIR.'/'.$filename);
        }
        
        return false;
    }
    
    /**
     * Checks if given file name is valid
     *
     * @param string $filename
     * @return bool
     */
    static function isValidFile($filename)
    {
        if (empty($filename)) return false;
        if (strpos($filename,'..')!==false) return false;
        
        return true;
    }
    
    /**
     * Returns uploaded files paginator
     *
     * @param int $page
     * @param int $limit
     * 
     * @return object
     */
    static function fetchFiles($page=1,$limit=10)
    {
        $dir=opendir(ROOT_DIR.'/'.self::UPLOAD_DIR);
        if (!$dir) return array();
        
        $files=array();
        while (($file=readdir($dir))!==false) 
        {
        	if ($file=='.' || $file=='..') continue;
        	
        	$files[]=$file;
        }
        
        closedir($dir);
        
        $adapter=new Zend_Paginator_Adapter_Array($files);
        
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber((int) $page);
        $paginator->setItemCountPerPage($limit);
        
        return $paginator;
    }
}

